package io.bluefw.blueui.dsl.render;

import java.io.IOException;
import java.io.StringWriter;

import javax.ws.rs.WebApplicationException;

import com.google.common.base.Charsets;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapperBuilder;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;

public class FreemarkerTemplate {
    private static final Version FREEMARKER_VERSION = Configuration.getVersion();
    private final LoadingCache<Class<?>, Configuration> configurationCache;
    private static final Supplier<FreemarkerTemplate> instance = Suppliers.memoize(new Supplier<FreemarkerTemplate>() {
        @Override
        public FreemarkerTemplate get() {
        	return new FreemarkerTemplate();
        }
    });
    
    private FreemarkerTemplate() {
        this.configurationCache = CacheBuilder.newBuilder()
                                              .concurrencyLevel(128)
                                              .build(new TemplateLoader());
    }
    
    private static class TemplateLoader extends CacheLoader<Class<?>, Configuration> {
        @Override
        public Configuration load(Class<?> key) throws Exception {
            final Configuration configuration = new Configuration(FREEMARKER_VERSION);
            configuration.setObjectWrapper(new DefaultObjectWrapperBuilder(FREEMARKER_VERSION).build());
            configuration.loadBuiltInEncodingMap();
            configuration.setDefaultEncoding(Charsets.UTF_8.name());
            configuration.setClassForTemplateLoading(key, "/");
            return configuration;
        }
    }

    public static FreemarkerTemplate getInstance() {
    	return instance.get();
    }
    
    public StringBuffer render(Object widget, String templateName) throws WebApplicationException {
        try {
            final Configuration configuration = configurationCache.getUnchecked(widget.getClass());
            final Template template = configuration.getTemplate(templateName, Charsets.UTF_8.name());
            StringWriter sw = new StringWriter();
            template.process(widget, sw);
            return sw.getBuffer();
        } catch (TemplateException | IOException e) {
            throw new WebApplicationException(e);
        } 
    }
}
